package com.settlement.system.controller;

import com.settlement.system.common.enums.ReturnStatusEnum;
import com.settlement.system.common.exception.ServiceException;
import com.settlement.system.common.annotation.LoggerProfile;
import com.settlement.system.model.param.ApiParams;
import com.settlement.system.model.entity.common.BaseModel;
import com.settlement.system.model.entity.common.BasePager;
import com.settlement.system.model.entity.common.SinglePage;
import com.settlement.system.reply.ListResponse;
import com.settlement.system.reply.ObjectDataResponse;
import com.settlement.system.common.util.common.BeanValidator;
import io.swagger.annotations.ApiOperation;
import jakarta.validation.ConstraintViolation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanMap;
import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.*;

/**
 * 组合了 api 和导出的Controller
 * @author
 * @param <ModelType>
 */
@Slf4j
public abstract class MergeApiExcelController<ModelType extends BaseModel, RequestType> extends ExcelController<ModelType> {

    /**
     * 保持
     *
     * @return
     */
    @ApiOperation(value = "新增")
    @LoggerProfile(methodNote="API接口新增")
    @RequestMapping(value = "/api/save", method = RequestMethod.POST)
    public ObjectDataResponse save(@RequestBody List<ModelType> list) {
        log.info("开始");
        try {
            clearBeanStringBlank(list);
            String message = verifyData(list);
            if (!StringUtils.isEmpty(message)) {
                return new ObjectDataResponse(ReturnStatusEnum.CHECK_FAILURE.getValue(), message);
            }
            setDefualt(list);
            baseService.saveNoDuplicateList(list);
        } catch (DuplicateKeyException ex) {
            log.info(ReturnStatusEnum.DUPLICATE_DATA.getText());
            return new ObjectDataResponse(ReturnStatusEnum.DUPLICATE_DATA.getValue(), ex.getMessage());
        } catch (ServiceException ex) {
            log.info(ReturnStatusEnum.REQUEST_ABNORMAL.getText());
            return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL.getValue(), ReturnStatusEnum.REQUEST_ABNORMAL.getText());
        }
        log.info("返回");
        return new ObjectDataResponse();
    }

    @ApiOperation(value = "test")
    @LoggerProfile(methodNote="test")
    @RequestMapping(value = "/api/test", method = RequestMethod.POST)
    public ObjectDataResponse test() {
        log.info("开始");
        try {
            log.info("just test!");
        } catch (DuplicateKeyException ex) {
            return new ObjectDataResponse(ReturnStatusEnum.DUPLICATE_DATA.getValue(), ex.getMessage());
        } catch (Exception ex) {
            return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL.getValue(), ReturnStatusEnum.REQUEST_ABNORMAL.getText());
        }
        log.info("返回");
        return new ObjectDataResponse();
    }

    /**
     * 验证数据
     *
     * @param list
     * @return
     */
    protected String verifyData(List<ModelType> list) {
        for (ModelType info : list) {
            ConstraintViolation violation = BeanValidator.validate(info);
            if (null != violation) {
                return info.toString() + ":" + violation.getMessage();
            }
        }
        return null;
    }

    protected<T> Map<String, Object> getRequestParam(T model) {
        if (model == null) {
            return new HashMap<>(16);
        } else if (model instanceof Map) {
            return (Map<String, Object>) model;
        } else {
            return new BeanMap(model);
        }
    }



    /**
     * 设置默认的值
     *
     * @param list
     */
    private void setDefualt(List<ModelType> list) {
        for (ModelType info : list) {
            info.setId(UUID.randomUUID().toString().replace("-", ""));
            info.setCreateUser("robot");
            info.setUpdateUser("robot");
            if(info.getCreateTime()==null){
                info.setCreateTime(new Date());
            }
            if(info.getUpdateTime()==null){
                info.setUpdateTime(new Date());
            }
        }
    }

    protected  String verifyBean(ApiParams t) {
        if(t==null){
            return "缺少bean参数";
        }
        return t.verify(t);
    }

    protected  String verifyBeans(List<? extends ApiParams> list) {
        if(CollectionUtils.isEmpty(list)){
            return "缺少bean参数";
        }
        for(ApiParams t : list){
            String message = t.verify(t);
            if(StringUtils.isNotBlank(message)){
                return message;
            }
        }
        return null;
    }

    public <T> String verifyBean(T t) {
        List<String> error = new ArrayList<>();
        ConstraintViolation validate = BeanValidator.validate(t);
        if (validate != null) {
            return validate.getMessage();
        }
        return null;
    }

    public <T> String verifyBean(List<T> list) {
        for(T t :list) {
            ConstraintViolation validate = BeanValidator.validate(t);
            if (validate != null) {
                return validate.getMessage();
            }
        }
        return null;
    }

    /**
     * 获取
     *
     * @return
     */
    @ApiOperation(value = "获取列表")
    @LoggerProfile(methodNote="获取列表")
    @RequestMapping(value = "/api/getList", method = RequestMethod.POST)
    public ObjectDataResponse<ListResponse<ModelType>> getList(@RequestBody BasePager<RequestType> model) {
        ListResponse<ModelType> result = new ListResponse<>();
        try {

            Map<String, Object> params = getRequestParam(model);
            setParamsModel(params);
            int count = baseService.selectCount(params);
            List<ModelType> rows = baseService.selectByPage(new SinglePage(model), params,
                    "id", "ASC");
            result.setTotal(count);
            result.setRows(rows);
        } catch (Exception ex) {
            log.error("获取列表出错", ex);
            return new ObjectDataResponse(500, "服务器异常");
        }
        return new ObjectDataResponse<ListResponse<ModelType>>(result, 200, "success");
    }

    /**
     * 获取请求参数
     *
     * @param model
     * @return
     */
    private Map<String, Object> getRequestParam(BasePager<RequestType> model) {
        if (model.getModel() == null) {
            return new HashMap<>(16);
        } else if (model.getModel() instanceof Map) {
            return (Map<String, Object>) model.getModel();
        } else {
            return new BeanMap(model.getModel());
        }
    }



}
